
package cn.ctyun.xstore.s3.api.bucket;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.BucketCrossOriginConfiguration;
import com.amazonaws.services.s3.model.CORSRule;

import cn.ctyun.xstore.s3.client.AwsS3ClientBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设置bucket的请求跨域方案
 */
public class SetBucketCrossOrigin {
    public static void setBucketCrossOrigin(String bucketName, AmazonS3 s3) {
        try {
            List<CORSRule.AllowedMethods> rule2AM = new ArrayList<>();
            rule2AM.add(CORSRule.AllowedMethods.PUT);
            rule2AM.add(CORSRule.AllowedMethods.GET);
            rule2AM.add(CORSRule.AllowedMethods.HEAD);
            CORSRule rule = new CORSRule().withId("CORSRule").withAllowedMethods(rule2AM)
                    .withAllowedOrigins(Arrays.asList("*"))
                    .withExposedHeaders(Arrays.asList("x-amz-server-side-encryption", "ETag", "x-amz-request-id", "Date",
                            "Content-Length", "Accept-Ranges", "Access-Control-Allow-Origin"))
                    .withAllowedHeaders(Arrays.asList("*"));
            List<CORSRule> rules = new ArrayList<>();
            rules.add(rule);
            BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();
            configuration.setRules(rules);
            s3.setBucketCrossOriginConfiguration(bucketName, configuration);
        } catch (AmazonServiceException e) {
            System.err.println(e.getErrorMessage());
        }
        System.out.println("Done!");
    }
}
